import { defineStore } from 'pinia';
import axios from '@/plugins/axios';
import { ElMessage } from 'element-plus';

export interface PaperSubmission {
  id: number;
  paperId: number;
  studentId: number;
  answers: { [key: string]: string };
  submitTime: string;
  status: 'SUBMITTED' | 'GRADED';
  score: number | null;
}

export interface PaperGradeRequest {
  submissionId: number;
  textQuestionScores: { [key: string]: string };
}

export const usePaperSubmissionStore = defineStore('paperSubmission', {
  state: () => ({
    paperSubmissions: [] as PaperSubmission[],
  }),

  actions: {
    async fetchSubmissions() {
      try {
        const response = await axios.get('/api/submission');
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '获取提交记录失败');
      } catch (error: any) {
        throw error;
      }
    },

    async fetchSubmissionsByStudent(studentId: number) {
      try {
        const response = await axios.get(`/api/submission/student/${studentId}`);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '获取学生提交记录失败');
      } catch (error: any) {
        throw error;
      }
    },

    async fetchSubmissionById(submissionId: number) {
      try {
        const response = await axios.get(`/api/submission/submission/${submissionId}`);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '获取提交记录失败');
      } catch (error: any) {
        throw error;
      }
    },

    async gradeSubmission(data: PaperGradeRequest) {
      try {
        const response = await axios.post('/api/submission/grade', data);
        if (response.data.code === 200) {
          ElMessage.success('评分提交成功');
          return response.data.data;
        }
        throw new Error(response.data.message || '评分提交失败');
      } catch (error: any) {
        ElMessage.error(error.message || '评分提交失败');
        throw error;
      }
    },
  },
});